// Package webmanage @author <chengjiang@buffalo-robot.com>
// @date 2023/2/21
// @note
package webmanage

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"
	"phm/internal/biz"
	"phm/internal/biz/webmanage"
	"phm/models/generator/model"
	"phm/models/generator/query"
)

type roleRepo struct {
	Db  biz.DataRepo
	log *log.Helper
}

func NewSysRoleRepo(data biz.DataRepo, logger log.Logger) webmanage.SysRoleRepo {
	return &roleRepo{Db: data, log: log.NewHelper(logger)}
}

func (u *roleRepo) CreateSysRole(ctx context.Context, uModel *model.SysRole, db *gorm.DB) error {
	var s = db
	if db == nil {
		s = u.Db.GetDB()
	}
	opt := query.Use(s).SysRole
	err := opt.WithContext(ctx).Create(uModel)
	if err != nil {
		return err
	}
	return nil
}

func (u *roleRepo) UpdateSysRole(ctx context.Context, uModel *model.SysRole, db *gorm.DB) error {
	var s = db
	if db == nil {
		s = u.Db.GetDB()
	}
	opt := query.Use(s).SysRole
	info, err := opt.WithContext(ctx).Where(opt.ID.Eq(uModel.ID)).Updates(uModel)
	u.log.Info(info)
	if err != nil {
		u.log.Errorf("更新角色错误：%v", err)
		return err
	}
	return nil
}

func (u *roleRepo) DeleteSysRoleByIds(ctx context.Context, ids []string, db *gorm.DB) error {
	var s = db
	if db == nil {
		s = u.Db.GetDB()
	}
	role := query.Use(s).SysRole
	info, err := role.WithContext(ctx).Where(role.ID.In(ids...)).Delete()
	u.log.Info(info)
	if err != nil {
		u.log.Errorf("删除错误：%v", ids)
		return err
	}
	return nil
}

func (u *roleRepo) GetSysRoleById(ctx context.Context, id string) (*model.SysRole, error) {
	s := u.Db.GetDB()
	opt := query.Use(s).SysRole
	user, err := opt.WithContext(ctx).Where(opt.IsSoftDelete.Eq(0), opt.ID.Eq(id)).First()
	if err != nil {
		return nil, err
	}
	return user, nil
}

func (u *roleRepo) GetSysRoleByIds(ctx context.Context, ids []string) ([]*model.SysRole, error) {
	s := u.Db.GetDB()
	opt := query.Use(s).SysRole
	users, err := opt.WithContext(ctx).Where(opt.IsSoftDelete.Eq(0), opt.ID.In(ids...)).Find()
	if err != nil {
		return nil, err
	}
	return users, nil
}

func (u *roleRepo) GetSysRoleByUserId(ctx context.Context, userId string) ([]*model.SysRole, error) {
	s := u.Db.GetDB()
	opt := query.Use(s).SysUserRole
	userRoles, err := opt.WithContext(ctx).Where(opt.IsSoftDelete.Eq(0), opt.UserID.Eq(userId)).Find()
	if err != nil {
		return nil, err
	}
	var roleIds = []string{}
	for _, v := range userRoles {
		roleIds = append(roleIds, *v.RoleID)
	}
	role := query.Use(s).SysRole
	roles, err := role.WithContext(ctx).Where(role.IsSoftDelete.Eq(0), role.ID.In(roleIds...)).Find()
	if err != nil {
		return nil, err
	}
	return roles, nil
}

func (u *roleRepo) GetDB() *gorm.DB {
	return u.Db.GetDB()
}
